<template>
  <view class="main">
    <view class="swiper">
      <van-swipe class="my-swipe" :autoplay="3000" :show-indicators="false">
        <van-swipe-item v-for="(item, index) in [detailData.backImage]" :key="index">
          <view class="images" :style="{
            background: 'url(' + item + ')',
            backgroundRepeat: 'no-repeat',
            backgroundSize: '100% 100%',
          }"></view>
          <!-- <image :src="item" mode="aspectFill" /> -->
        </van-swipe-item>
      </van-swipe>
      <view class="back" @click="switchTabbarChange">
        <van-icon name="arrow-left" color="#111" size="30" />
      </view>
    </view>
    <view class="desc">
      <view class="title-box">
        <view class="title-text">{{ detailData.name }}</view>
        <!-- <view class="good-box dispaly-center">
                    <view class="good-number">100%</view>
                    <view class="good-text">好评率</view>
                </view> -->
      </view>
      <view class="option">
        <view class="option-block dispaly-center">
          <view class="option-left">
            <image src="/static/icon/time.svg" mode="widthFix" />
          </view>
          <view class="option-line"></view>
          <view class="option-right">
            <view class="option-title">已运营时间</view>
            <view class="option-number">{{ detailData.days }}天</view>
          </view>
        </view>
        <view class="option-block dispaly-center">
          <view class="option-left">
            <image src="/static/icon/fir.svg" mode="widthFix" />
          </view>
          <view class="option-line"></view>
          <view class="option-right">
            <view class="option-title">加入圈子人数 </view>
            <view class="option-number">{{ detailData.memberNum }}人</view>
          </view>
        </view>
      </view>
      <view class="option">
        <view class="option-block dispaly-center">
          <view class="option-left">
            <image src="/static/icon/file.svg" mode="widthFix" />
          </view>
          <view class="option-line"></view>
          <view class="option-right">
            <view class="option-title">社区动态咨询</view>
            <view class="option-number"> {{ detailData.trendsNum }} 篇</view>
          </view>
        </view>
        <view class="option-block dispaly-center">
          <view class="option-left">
            <image src="/static/icon/z-time.svg" mode="widthFix" />
          </view>
          <view class="option-line"></view>
          <view class="option-right">
            <view class="option-title">最新更新时间</view>
            <view class="option-number">{{ detailData.updateTime }}</view>
          </view>
        </view>
      </view>
      <view class="detail" style="padding: 30rpx; padding-bottom: 10rpx">
        <view class="tule-title">
          <text>圈子介绍</text>
        </view>
      </view>
      <view class="detail" style="padding: 30rpx; padding-top: 10rpx">
        <rich-text :nodes="detailData.brief"></rich-text>
      </view>
      <view class="detail" style="padding: 30rpx; padding-bottom: 10rpx">
        <view class="tule-title">
          <text>圈子价值</text>
        </view>
      </view>
      <view class="detail" style="padding: 30rpx; padding-top: 10rpx">
        <rich-text :nodes="detailData.effect"></rich-text>
      </view>
      <view class="detail" style="padding: 30rpx">
        <view class="tule-title">
          <text>收费规则</text>
        </view>
        <view clas="rule-content">
          <view class="rule-list custom-rule">
            <text>1、本圈子定价:</text>
            <text>￥{{ detailData?.serviceFee?.toFixed(2) }}/永久 </text>
          </view>
          <view class="rule-list custom-rule">
            <text>2、圈子为虚拟商品，如有疑问请联系相关运营人员</text>
          </view>
          <view class="rule-list custom-rule">
            <text>3.加入即代表同意</text>
            <text class="color-blank" @click="$goUrl(`/pages/login/addressBookDoc`)">《汇友互助用户协议》</text>
            <text>和</text>
            <text class="color-blank" @click="$goUrl(`/pages/login/refundTready`)">《付款及退款规则》</text>
          </view>
        </view>
      </view>
    </view>
  </view>
  <view class="btn-box dispaly-center">
    <view class="tel dispaly-col-center" @click="callOwner">
      <image src="/static/icon/mesg1.png" mode="aspectFill" />
      <view class="tel-text">联系群主 </view>
    </view>
    <view class="btn">
      <!-- detailData.serviceFee != null && || isPay != -1 -->
      <Button v-if="isPay != '-1'" @clickButton="addGroup" text="进入圈子" :block="false" />
      <Button @clickButton="addGroup" :loading="loading" v-else loading-text="加载中" :text="detailData.serviceFee != null
        ? '加入圈子¥' + detailData.serviceFee
        : '加入圈子¥0'
        " :block="false" />
    </view>
  </view>
  <van-popup v-model:show="show">
    <view class="pop-main">
      <view class="pop-content">
        <view class="pop-desc dispaly-col-center">
          <view class="one-title">真的要放弃这个机会吗？</view>
          <view class="two-title">增加100个人脉，有可能帮你增长1万生意哦</view>
          <view class="three-title">已有10个用户用一顿饭的钱</view>
          <view class="three-title">为自己增加了100+潜客资源</view>
        </view>
        <view class="pop-btn dispaly-just-between">
          <view class="btn-con one dispaly-align-center" @click="show = false">关注公众号</view>
          <view class="btn-con two dispaly-align-center" @click="
            () => {
              addGroup();
              show = false;
            }
          ">继续支付</view>
        </view>
      </view>
    </view>
  </van-popup>

  <van-popup v-model:show="callShow" height="800">
    <view class="pop-main dispaly-col-center" style="padding: 30rpx">
      <image show-menu-by-longpress :src="consultImg" style="width: 560rpx" mode="aspectFill" />
      <view class="tip" style="margin-top: 30rpx" @click="copy(consultTig)">{{ consultTig }}</view>
    </view>
  </van-popup>

  <van-popup v-model:show="shouLogin" close-icon="close" :style="{ padding: '80rpx 60rpx 0 60rpx' }">
    <van-field class="van-popup-input" v-model="phonenumber" type="number" maxlength="11" label=""
      placeholder="请输入您的手机号" />
    <view class="footer-btns">
      <view class="btn" @click="shouLogin = false">取消</view>
      <view class="btn" @click="loginUser">确定</view>
    </view>
  </van-popup>
</template>

<script setup>
import { ref } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import {
  circleInfo,
  addCircle,
  proxy,
  fillCircle,
  getUserInfo,
  circleBaseInfo,
  getPayStat,
  miniPay,
  scanLogin,
} from "@/api/apiList";
import { deleteObjectEmptyKey } from "@/utils/util";

// 复制微信
const copy = (text) => {
  uni.setClipboardData({
    data: text,
    success: () => {
      callShow.value = false;
      uni.showToast({
        title: "复制成功",
        icon: "none",
      });
    },
  });
};

let shouLogin = ref(false);
let phonenumber = ref("");
const userInfo = ref({});
const getUserInfoData = async (cId) => {
  const res = await getUserInfo();
  if (res.code == 200) {
    userInfo.value = res.data;
    const circleIds = userInfo.value.circleIds;
    console.log(circleIds);
    if (circleIds) {
      isPay.value = circleIds.findIndex((item) => item == cId);
      console.log(isPay.value, "isPay.value");
    } else {
      isPay.value = "-1";
    }
  }
};

const id = ref("");
const isPay = ref(-1);
const getInfo = ref();
const circleIDS = ref();
// 请求表单项目
onLoad(async (option) => {
  formData.value.circleId = (await option?.circleId)
    ? option?.circleId
    : option.id;
  formData.value.userId = option.userId ? option.userId : "";
  id.value = option.id;
  uni.setStorageSync("weixinUserId", option.userId ? option.userId : "");

  circleIDS.value = option.circleId;
  getInfo.value = uni.getStorageSync("token");
  getData();
  if (uni.getStorageSync("token")) {
    await getUserInfoData(formData.value.circleId);
    // getConfig("consultTig,consultImg");
    getForm();
  }
});

onShow(() => {
  setTimeout(() => {
    getData();
  }, 300);
});

// 登录
const loginUser = async () => {
  let reg = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/;
  if (phonenumber.value == "") return showToast("请输入您的手机号");
  if (reg.test(phonenumber.value) != true)
    return showToast("手机号码格式不正确");
  const res = await scanLogin({ phonenumber: phonenumber.value });
  if (res.code != 200) {
    shouLogin.value = false;
    return showToast("登录失败");
  }
  uni.setStorageSync("token", res.msg);
  uni.showToast({
    title: "登录成功",
    icon: "none",
  });
  shouLogin.value = false;
  let result = await getUserInfo();

  if (result.code != 200) {
    uni.setStorageSync("token", "");
    return showToast("获取用户信息失败");
  }
  // formData.userId = result.data.userId;
  uni.setStorageSync("userInfo", result.data);
  userInfo.value = result.data;
  let circleIds = result.data.circleIds;
  if (circleIds) {
    isPay.value = circleIds.findIndex(
      (item) => item == formData.value.circleId
    );
  } else {
    isPay.value = "-1";
  }
  if (isPay.value == "-1") {
    // 没有支付 登录了 直接调支付
    addGroup();
  } else {
    // 支付了
    getData();
  }
};

const resultData = ref([]);
const getForm = async () => {
  const result = await fillCircle({ id: formData.value.circleId });
  if (result.code == 200) {
    resultData.value = result.data;
  }
};

const consultTig = ref("");
const consultImg = ref("");
const getConfig = async (data) => {
  const res = await proxy(data);
  if (res.code == 200) {
  }
};

const detailData = ref({});
const getMoney = ref();
const getData = async () => {
  const res = await circleBaseInfo({
    id: circleIDS.value ? circleIDS.value : id.value,
    isApp: "true",
    userId: userInfo.value.userId,
  });
  // console.log(1111111111111111);
  // console.log(res.data);
  // return false;

  if (res.code == 200) {
    detailData.value = res.data;
    if (res.data.wxQrCode) {
      consultImg.value = res.data.wxQrCode;
    }
    if (res.data.qrCodeUrl) {
      consultImg.value = res.data.qrCodeUrl;
    }
    consultTig.value = res.data.wx;
    formData.value.totalAmount = res.data.serviceFee;
    detailData.value.brief = detailData.value?.brief?.replace(
      /\<img/gi,
      '<img style="max-width:100%;height:auto" '
    );

    if (
      !res.data.isFill &&
      userInfo.value.userId != res.data.createUser &&
      isPay.value != "-1" &&
      resultData.value.length
    ) {
      uni.navigateTo({
        url: `/pages/index/pages/addForm?id=${formData.value.circleId}`,
      });
    } else {
      if (isPay.value != "-1") {
        // 关闭当前页面跳转
        uni.redirectTo({
          url: `/pages/circle/pages/groupConsole?id=${formData.value.circleId}`,
        });
      }
    }
  }
};

// 联系群主
const callShow = ref(false);
const callOwner = () => {
  // if (isPay.value != -1 || detailData.value.serviceFee == null || detailData.value.serviceFee == 0) {
  callShow.value = true;
  // } else {
  //     uni.showToast({
  //         title: '您尚未加入圈子',
  //         icon: 'none'
  //     })
  // }
};

let show = ref(false);

const loading = ref(false);
const formData = ref({
  circleId: "",
  userId: "",
  subject: "加入圈子",
  totalAmount: "",
});

const getOpenChangeStatus = () =>
  new Promise((resolve, reject) => {
    getPayStat(detailData.value.id).then((res) => {
      if (res.code == 200) {
        return resolve(res);
      }
    });
  });

const addGroup = async () => {
  const ua = navigator.userAgent.toLowerCase();
  /* if (
    ua.match(/MicroMessenger/i) == "micromessenger" &&
    !uni.getStorageSync("token")
  ) {
    return uni.showModal({
      title: "系统提示",
      content: "因微信支付要求，需要您从登录页面进入，点击确定立即跳转",
      showCancel: true,
      success: function (res) {  
        // 存储跳回地址
        uni.setStorageSync("loginBackUrl","/pages/index/pages/groupDetail?id="+formData.value.circleId)
        uni.navigateTo({
          url: "/pages/login/login",
        });
      },
    });
  } */
  // 如果没有登录或者没有支付  需要跳转支付
  if (!uni.getStorageSync("token")) {
    return (shouLogin.value = true);
  }

  loading.value = true;
  const newForm = deleteObjectEmptyKey(formData.value);

  // 微信支付
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    uni.setStorageSync("payId", formData.value.circleId);
    loading.value = false;
    // 跳转页面
    uni.navigateTo({
      url: "/pages/forSale/pages/weixinPay?id" + formData.value.circleId,
    });
  } else {
    // 阿里支付
    miniPay({
      ...newForm,
      totalAmount: formData.value.totalAmount ? formData.value.totalAmount : 0,
    })
      .then(async (res) => {
        loading.value = false;
        if (res.code == 200) {
          if (res.msg) {
            uni.setStorageSync("resFrom", res.msg);
            uni.setStorageSync("AliPayId", formData.value.circleId);

            uni.navigateTo({
              url: "/pages/forSale/pages/Alipay?id=" + formData.value.circleId,
            });
          }
        } else {
          loading.value = false;
        }
      })
      .catch((err) => {
        loading.value = false;
      });
  }

  return false;

  if (isPay.value != -1) {
    uni.navigateTo({
      url: `/pages/circle/pages/groupConsole?id=${detailData.value.id}`,
    });
  } else {
    loading.value = true;
    const newForm = deleteObjectEmptyKey(formData.value);
    const ua = navigator.userAgent.toLowerCase();

    if (ua.match(/MicroMessenger/i) == "micromessenger") {
      const res = await addCircle(newForm);
      if (res.code == 200) {
        // const { h5_url } = res.data
        if (res.data.h5_url) {
          uni.setStorageSync("resFrom", res.data.h5_url);
          uni.navigateTo({
            url: "/pages/forSale/pages/Alipay?id=" + formData.value.circleId,
          });
        }
        getOpenChangeStatus().then(async (res) => {
          const result = await fillCircle({ id: detailData.value.id });
          if (res.data.payStats == 1) {
            if (result.code == 200) {
              if (result.data.length) {
                if (detailData.value.isFill == 1) {
                  uni.navigateTo({
                    url: `/pages/circle/pages/groupConsole?id=${detailData.value.id}`,
                  });
                } else {
                  uni.navigateTo({
                    url: `/pages/index/pages/addForm?id=${detailData.value.id}`,
                  });
                }
              } else {
                uni.navigateTo({
                  url: `/pages/circle/pages/groupConsole?id=${detailData.value.id}`,
                });
              }
              // if (h5_url) {
              //     if (result.data.length) {
              //         if (detailData.value.isFill == 1) {
              //             uni.navigateTo({
              //                 url: `/pages/circle/pages/groupConsole?id=${detailData.value.id}`
              //             })
              //         } else {
              //             uni.navigateTo({
              //                 url: `/pages/index/pages/addForm?id=${detailData.value.id}`
              //             })
              //         }
              //     } else {
              //         uni.navigateTo({
              //             url: `/pages/circle/pages/groupConsole?id=${detailData.value.id}`
              //         })
              //     }
              // } else {
              //     if (result.data.length) {
              //         if (detailData.value.isFill == 1) {
              //             uni.navigateTo({
              //                 url: `/pages/circle/pages/groupConsole?id=${detailData.value.id}`
              //             })
              //         } else {
              //             uni.navigateTo({
              //                 url: `/pages/index/pages/addForm?id=${detailData.value.id}`
              //             })
              //         }
              //     } else {
              //         uni.navigateTo({
              //             url: `/pages/circle/pages/groupConsole?id=${detailData.value.id}`
              //         })
              //     }
              // }
            }
          }
        });
        loading.value = false;
      } else {
        loading.value = false;
      }
    } else {
      miniPay({
        ...newForm,
        totalAmount: formData.value.totalAmount
          ? formData.value.totalAmount
          : 0,
      })
        .then(async (res) => {
          loading.value = false;
          if (res.code == 200) {
            if (res.msg) {
              uni.setStorageSync("resFrom", res.msg);
              uni.navigateTo({
                url:
                  "/pages/forSale/pages/Alipay?id=" + formData.value.circleId,
              });
            }
          } else {
            loading.value = false;
          }
        })
        .catch((err) => {
          loading.value = false;
        });
    }
  }
};

const inCircle = () => {
  uni.navigateTo({
    url: `/pages/circle/pages/groupConsole?id=${detailData.value.id}`,
  });
};

const switchTabbarChange = () => {
  uni.switchTab({
    url: "/pages/index/index",
  });
};
</script>

<style lang="scss" scoped>
:deep(.van-popup--center) {
  border-radius: 16rpx;
}

.btn-box {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  height: 166rpx;
  padding: 0 30rpx;

  .tel-text {
    font-size: 28rpx;
    margin-top: 15rpx;
  }

  .tel {
    flex: 1;

    image {
      width: 35rpx;
      height: 35rpx;
    }
  }

  .btn {
    flex: 4;
  }
}

.pop-main {
  .pop-content {
    border-radius: 16rpx;
    background: #ffffff;
    border-radius: 16rpx;
    .pop-desc {
      padding: 64rpx 76rpx 0 76rpx;

      .one-title {
        font-family: PingFang SC Bold;
        font-size: 32rpx;
        font-weight: 700;
        color: #111111;
      }

      .two-title {
        margin: 16rpx 0 60rpx 0;
        font-family: PingFang SC Medium;
        font-size: 24rpx;
        font-weight: normal;
        color: #999999;
      }

      .three-title {
        font-family: PingFang SC Medium;
        font-size: 28rpx;
        font-weight: normal;
        color: #111111;
      }

      .three-title:last-child {
        margin-bottom: 46rpx;
      }
    }

    .pop-btn {
      border-top: 1rpx solid #eeeeee;

      .one,
      .two {
        font-family: PingFang SC Medium;
        font-size: 34rpx;
      }

      .one {
        color: #999999;
        border-right: 1rpx solid #eee;
      }

      .two {
        color: #0753fd;
      }

      .btn-con {
        padding: 30rpx 0;
        width: 50%;
      }
    }
  }
}

.main {
  position: relative;

  .detail {
    padding-bottom: 166rpx;

    text {
      &:nth-child(2) {
        color: red;
      }
    }
  }

  .swiper {
    position: relative;

    image {
      width: 100%;
      height: 586rpx;
    }

    .back {
      position: absolute;
      left: 10rpx;
      top: 30rpx;
    }
  }

  .desc {
    position: absolute;
    left: 0;
    right: 0;
    top: 570rpx;
    padding-bottom: 200rpx;

    .title-box {
      background-color: #fff;
      padding: 46rpx 15rpx 32rpx 15rpx;
      border-radius: 20rpx 20rpx 0px 0px;

      .title-text {
        font-family: PingFang SC Heavy;
        font-size: 32rpx;
        font-weight: 700;
        color: #111111;
      }

      .good-box {
        background: #f5ead8;
        width: 160rpx;
        margin-top: 26rpx;
        border-radius: 8rpx;

        .good-number {
          font-family: PingFang SC Heavy;
          font-size: 30rpx;
          font-weight: normal;
          color: #8c5b3f;
          background: #efd0a5;
          border-radius: 8rpx;
          padding: 4rpx;
        }

        .good-text {
          font-family: PingFang SC Medium;
          font-size: 24rpx;
          font-weight: normal;
          color: #8c5b3f;
          padding: 4rpx;
          width: 100%;
          text-align: center;
        }
      }
    }

    .option {
      display: flex;
      align-items: center;
      justify-content: space-between;
      // flex-wrap: wrap;
      margin: 20rpx 0;
      padding: 0 15rpx;

      .option-block:first-child {
        margin-right: 11rpx;
      }

      .option-block {
        width: 334rpx;
        // margin: 11rpx;
        // width: calc(33.333% - 11rpx);
        // margin: 0 11rpx;
        border-radius: 16rpx;
        background: #fff;
        padding: 20rpx 24rpx;

        .option-left {
          image {
            width: 40rpx;
            height: 40rpx;
          }
        }

        .option-line {
          width: 2rpx;
          height: 40rpx;
          background: #eeeeee;
          margin: 0 24rpx;
        }

        .option-right {
          .option-title {
            font-family: PingFang SC Medium;
            font-size: 20rpx;
            font-weight: normal;
            color: #999999;
            margin-bottom: 14rpx;
          }

          .option-number {
            font-family: PingFang SC Heavy;
            font-size: 22rpx;
            font-weight: 700;
            color: #0753fd;
            white-space: nowrap;
          }
        }
      }
    }
  }
}

.custom-rule {
  margin: 20rpx 0;

  text {
    color: #333;
    font-size: 30rpx;
  }
}

.color-blank {
  color: #0753fd !important;
}

.van-popup-input {
  border: 1rpx #333 solid;
  border-radius: 10rpx;
}

.footer-btns {
  display: flex;
  margin-top: 60rpx;

  .btn {
    flex: 1;
    text-align: center;
    height: 100rpx;
    line-height: 60rpx;
  }

  .btn:first-of-type {
    //border-right: 1rpx solid #333;
    box-sizing: border-box;
    color: #333;
  }

  .btn:last-of-type {
    color: #004fff;
  }
}

.images {
  display: block;
  width: 100%;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  height: 586rpx;
}
</style>
